<template>
  <view class="filterArea">
    <!-- 动态生成筛选器 -->
    <view 
      v-for="(level, levelIndex) in filterLevels" 
      :key="levelIndex"
      class="select-wrap"
      :data-level="levelIndex"
    >
      <view
        class="select-btn"
        :class="{ 
          disabled: isLevelDisabled(levelIndex),
          'single-option': level.options.length === 1 
        }"
        @click="handleLevelClick(levelIndex)"
      >
        <view 
          class="select-text"
          @longpress="showTextModal(levelIndex)"
        >{{ getLevelDisplayText(levelIndex) }}</view>
      </view>
      <image 
        v-if="!isLevelDisabled(levelIndex)"
        class="arrow-img" 
        src="/static/img/components/arrow.png" 
        mode="widthFix" 
      />
      <view 
        v-show="dropdownOpen === levelIndex && !isLevelDisabled(levelIndex)" 
        class="select-dropdown"
      >
        <view
          v-for="(item, idx) in level.options"
          :key="item.value"
          class="select-option"
          :class="{ active: idx === level.selectedIndex }"
          @click="selectLevel(levelIndex, idx)"
        >
          {{ item.label }}
        </view>
      </view>
    </view>
  </view>
  
  <!-- 遮罩层，点击关闭下拉 -->
  <view
    v-if="dropdownOpen !== null"
    class="dropdown-mask"
    @touchstart.stop="closeDropdown"
    @mousedown.stop="closeDropdown"
  ></view>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, computed, nextTick } from 'vue';

// 定义props
const props = defineProps({
  // 筛选配置
  filterConfig: {
    type: Object,
    default: () => ({
      maxLevels: 3, // 最大层级数
      labels: ['区域', '子区域', '子子区域'], // 各级标签
    }),
  },
  // 区域数据 - 支持多级嵌套结构
  areaData: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(['filterChange']);

// 筛选层级数据
const filterLevels = ref([]);
const dropdownOpen = ref(null);

// 计算最大层级数
const actualMaxLevels = computed(() => {
  return props.filterConfig?.maxLevels || 3;
});

// 显示文本弹窗
const showTextModal = (levelIndex) => {
  const level = filterLevels.value[levelIndex];
  if (!level || !level.options.length) return;
  
  const selectedOption = level.options[level.selectedIndex];
  const text = selectedOption?.label || '';
  
  if (text) {
    uni.showToast({
      title: text,
      icon: 'none',
      duration: 4000
    });
  }
};



// 初始化筛选层级
const initFilterLevels = () => {
  const levels = [];
  
  if (props.areaData && props.areaData.length > 0) {
    buildLevelsFromAreaData(levels);
  }
  
  filterLevels.value = levels;
};

// 从 areaData 构建筛选层级
const buildLevelsFromAreaData = (levels) => {
  // 第一级：从 areaData 获取
  if (props.areaData.length > 0) {
    levels.push({
      level: 0,
      label: props.filterConfig?.labels?.[0] || '区域',
      options: props.areaData.map(item => ({
        label: item.label,
        value: item.value,
        children: item.children || []
      })),
      selectedIndex: 0,
      selectedValue: props.areaData[0]?.value || ''
    });
  }
  
  // 动态构建后续层级（初始状态下构建所有可能的层级）
  for (let i = 1; i < actualMaxLevels.value; i++) {
    const prevLevel = levels[i - 1];
    
    if (prevLevel && prevLevel.options.length > 0) {
      const selectedOption = prevLevel.options[prevLevel.selectedIndex];
      const children = selectedOption?.children || [];
      
      if (children.length > 0) {
        levels.push({
          level: i,
          label: props.filterConfig?.labels?.[i] || `子区域${i}`,
          options: children.map(item => ({
            label: item.label,
            value: item.value,
            children: item.children || []
          })),
          selectedIndex: 0,
          selectedValue: children[0]?.value || ''
        });
      } else {
        // 如果没有子级，停止构建
        break;
      }
    } else {
      // 如果前一级没有选项，停止构建
      break;
    }
  }
};

// 判断层级是否禁用
const isLevelDisabled = (levelIndex) => {
  const level = filterLevels.value[levelIndex];
  if (!level) return true;
  
  // 如果只有一个选项，则禁用（适用于所有层级）
  if (level.options.length === 1) return true;
  
  // 如果没有选项，则禁用
  if (level.options.length === 0) return true;
  
  return false;
};

// 处理层级点击
const handleLevelClick = (levelIndex) => {
  if (isLevelDisabled(levelIndex)) return;
  toggleDropdown(levelIndex);
};

// 切换下拉菜单
const toggleDropdown = (levelIndex) => {
  dropdownOpen.value = dropdownOpen.value === levelIndex ? null : levelIndex;
};

// 关闭下拉菜单
const closeDropdown = () => {
  dropdownOpen.value = null;
};

// 选择层级选项
const selectLevel = (levelIndex, optionIndex) => {
  const level = filterLevels.value[levelIndex];
  if (!level) return;
  
  level.selectedIndex = optionIndex;
  level.selectedValue = level.options[optionIndex]?.value || '';
  
  // 重置后续层级的选择
  for (let i = levelIndex + 1; i < filterLevels.value.length; i++) {
    const nextLevel = filterLevels.value[i];
    if (nextLevel) {
      nextLevel.selectedIndex = 0;
      nextLevel.selectedValue = nextLevel.options[0]?.value || '';
    }
  }
  
  // 重新构建后续层级
  rebuildSubsequentLevels(levelIndex);
  
  closeDropdown();
  
  // 发射筛选变化事件
  emitFilterChange(levelIndex);
};

// 重新构建后续层级
const rebuildSubsequentLevels = (fromLevelIndex) => {
  // 移除后续层级
  filterLevels.value.splice(fromLevelIndex + 1);
  
  // 重新构建后续层级
  let currentLevelIndex = fromLevelIndex;
  while (currentLevelIndex + 1 < actualMaxLevels.value) {
    const currentLevel = filterLevels.value[currentLevelIndex];
    if (currentLevel && currentLevel.options.length > 0) {
          const selectedOption = currentLevel.options[currentLevel.selectedIndex];
    const children = selectedOption?.children || [];
    
    if (children.length > 0) {
      filterLevels.value.push({
        level: currentLevelIndex + 1,
        label: props.filterConfig?.labels?.[currentLevelIndex + 1] || `子区域${currentLevelIndex + 1}`,
        options: children.map(item => ({
          label: item.label,
          value: item.value,
          children: item.children || []
        })),
        selectedIndex: 0,
        selectedValue: children[0]?.value || ''
      });
        currentLevelIndex++;
      } else {
        // 如果没有子级，停止构建
        break;
      }
    } else {
      // 如果当前级别没有选项，停止构建
      break;
    }
  }
};

// 发射筛选变化事件
const emitFilterChange = (levelIndex) => {
  const level = filterLevels.value[levelIndex];
  if (!level) return;
  
  // 构建筛选数据
  const filterData = {
    type: `filter${levelIndex + 1}`,
    [`filter${levelIndex + 1}`]: level.options[level.selectedIndex],
    targetIndex: level.selectedIndex,
  };
  
  emit('filterChange', filterData);
};

// 获取层级显示文本
const getLevelDisplayText = (levelIndex) => {
  const level = filterLevels.value[levelIndex];
  if (!level || !level.options.length) return '';
  
  const selectedOption = level.options[level.selectedIndex];
  return selectedOption?.label || '';
};

// 更新层级索引（供父组件调用）
const updateLevelIndex = (levelIndex, newIndex) => {
  const level = filterLevels.value[levelIndex];
  if (level && newIndex >= 0 && newIndex < level.options.length) {
    level.selectedIndex = newIndex;
    level.selectedValue = level.options[newIndex]?.value || '';
  }
};

// 监听 props 变化
watch(
  () => [props.areaData, props.filterConfig],
  () => {
    initFilterLevels();
  },
  { deep: true, immediate: true }
);

// 暴露方法给父组件
defineExpose({
  filterLevels, // 暴露筛选层级数据
  updateLevelIndex,
});

// 组件挂载后初始化
onMounted(() => {
  initFilterLevels();
});

// 组件卸载时清理
onUnmounted(() => {
  // 无需特殊清理
});


</script>

<style>
.filterArea {
  width: 100%;
  min-height: 40rpx;
  background-color: transparent;
  display: flex;
  justify-content: space-around;
  align-items: center;
  position: relative;
  z-index: 20;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  
  .select-wrap {
    position: relative;
    min-width: 180rpx;
    flex: 1;
    max-width: calc(33.33% - 14rpx);
    margin-bottom: 10rpx;
    display: flex;
    align-items: center;
    
    .select-btn {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      font-size: 28rpx;
      color: #fff;
      font-weight: 400;
      border-radius: 12rpx;
      transition: all 0.2s;
      min-width: 180rpx;
      flex: 1; /* 为箭头留出空间 */
      overflow: hidden; /* 隐藏超出容器的文本 */
      
      /* 文本容器，让文本从左开始显示 */
      .select-text {
        text-align: left;
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: block;
        min-width: 0; /* 允许容器收缩 */
      }

      &.disabled {
        color: #666;
        cursor: not-allowed;
      }
      
      &.single-option {
        color: #999;
        cursor: not-allowed;
      }

      .arrow {
        font-size: 24rpx;
        margin-left: 8rpx;
        color: #fff;
      }
    }
    
    .select-dropdown {
      position: absolute;
      left: 0;
      top: 100%;
      min-width: 100%;
      max-width: 50vw;
      background: #1a3a6a;
      border-radius: 12rpx;
      box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
      z-index: 100;
      margin-top: 8rpx;
      max-height: 300rpx;
      overflow-y: hidden;
      
      .select-option {
        padding: 20rpx 24rpx;
        text-align: left;
        font-size: 28rpx;
        color: #fff;
        cursor: pointer;
        transition: background 0.2s;
        border-bottom: 1rpx solid #2a4a7a;
        white-space: nowrap;
        
        &:last-child {
          border-bottom: none;
        }
      }
      
      .select-option.active,
      .select-option:hover {
        color: #1ec8e1;
        background: #2a4a7a;
        font-weight: bold;
      }
      
      /* 自定义滚动条样式 */
      &::-webkit-scrollbar {
        width: 8rpx;
      }
      
      &::-webkit-scrollbar-track {
        background: #1a3a6a;
        border-radius: 4rpx;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #2a4a7a;
        border-radius: 4rpx;
      }
      
      &::-webkit-scrollbar-thumb:hover {
        background: #1ec8e1;
      }
    }
  }
}

.dropdown-mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100vh;
  z-index: 10;
}

.arrow-img {
  width: 24rpx;
  height: 14rpx;
  flex-shrink: 0; /* 防止箭头被压缩 */
  display: inline-block;
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

/* 移除滚动文本样式，使用CSS省略号 */
</style>
